<template>
	<view class="content bg-#F6F9F8 h-100vh photo_back_1">

		<custom_navbar :title="navbar_title" @getNavHeight="getNavHeight" theme="light" />

		<view class="photo_s2_1" v-if="loaded && cameraEnable">

			<camera flash="auto" :device-position="devicePosition" @error="errorCamera"
				style="width: 100%; height: 100%;">
			</camera>

		</view>

		<view class="photo_s2_1" v-else style="overflow: hidden;">
			<view style="display: flex;justify-content: center;margin-top: 200rpx;overflow:hidden;">请授权使用摄像头</view>


		</view>


		<view class="photo_s2_2">
			请将人脸置于取景框内
		</view>

		<view class="photo_s2_3">
			<view class="photo_s2_3_one" v-for="(item,index) in step_2">
				<view class="photo_s2_3_one_1">
					<image :src="item.img" />
				</view>
				<view class="photo_s2_3_one_2">{{item.title}}</view>
			</view>
		</view>


		<view class="photo_s2_4">
			<view class="photo_s2_4_one" v-for="(item,index) in step_3">
				<view class="photo_s2_4_one_1">
					<image :src="item.img1" />
				</view>
				<view class="photo_s2_4_one_2">
					<view class="photo_s2_4_one_2_1">
						<image :src="item.img2" />
					</view>
					<view class="photo_s2_4_one_2_2">{{item.title}}</view>

				</view>
			</view>
		</view>

		<view class="photo_s2_5" @tap="takePhoto()">
			<image src="/static/images/photo_13.png" />
		</view>
		<view class="photo_s2_6">

		</view>
	</view>

</template>

<script>
	import {
		navigateTo,
		navigateBack
	} from "@/hooks";
	import custom_navbar from "./components/photo.vue";
	// import uParse from '@/components/u-parse/u-parse.vue';
	import store from "@/store";

	import {
		ossurl,
		photoUploadFile,
		getImgInfo,
		compressImg
	} from '@/utils/index';


	export default {
		components: {
			custom_navbar
			// uParse
		},
		data() {
			return {
				loaded: false,
				cameraEnable: true,
				loop: false,
				navigateTo,
				navigateBack,
				navbar_title: "AI旅拍",
				statusBarHeight: 20,
				cameraContext: {},
				devicePosition: "front",
				err: [],
				spot_id: '',
				points_id: '',
				from_index: '',
				again: 0,
				again_model: 0,
				use_camera: 1,
				step_2: [{
						"title": '保持光线充足',

						'img': '/static/images/photo_12.png'
					},
					{
						"title": '请面对屏幕',

						'img': '/static/images/photo_14.png'
					},
					{
						"title": '面带微笑',

						'img': '/static/images/photo_15.png'
					}
				],

				step_3: [{
						"title": '五官清晰',

						'img1': '/static/images/photo_7.png',
						'img2': '/static/images/photo_16.png'
					},
					{
						"title": '不是正面',

						'img1': '/static/images/photo_10.png',
						'img2': '/static/images/photo_11.png'
					},
					{
						"title": '面部遮挡',

						'img1': '/static/images/photo_9.png',
						'img2': '/static/images/photo_11.png'
					},
					{
						"title": '照片模糊',

						'img1': '/static/images/photo_8.png',
						'img2': '/static/images/photo_11.png'
					},
				],

			};
		},
		computed: {
			rec_url() {
				return this.$store.getters.rec_url;
			},
			ai_photo() {
				return uni.getStorageSync('aiPhoto');
			}

		},


		mounted() {
			let that = this;
			const info = uni.getSystemInfoSync();
			that.statusBarHeight = info.statusBarHeight + 43;
			setTimeout(() => {
				this.loaded = true;
				this.loopGetCameraInfo();
			}, 500);
		},

		onShow() {
			if (this.loaded && !this.loop) {
				// 轮询当前相机权限状态，当用户授权则将cameraEnable设置为true
				this.loopGetCameraInfo();
			}
		},
		onLoad(options) {
			this.spot_id = options.spot_id;
			this.points_id = options.points_id;
			this.again_model = options.am ? options.am : 0;
			this.from_index = options.i;
			this.again = options.again;

			if (uni.createCameraContext) {
				this.cameraContext = uni.createCameraContext()
			} else {
				// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
				uni.showModal({
					title: '提示',
					content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
				})
			}


			//this.errorCamera()
		},
		methods: {

			// 获取头的高度
			getNavHeight(e) {
				this.NavHeight_infoHeight += e;
			},

			loopGetCameraInfo() {
				this.loop = true;
				this.getCameraAuthInfo();
				setTimeout(() => {
					if (!this.loaded) {
						this.loopGetCameraInfo();
					} else {
						if (!this.cameraEnable) {
							this.loopGetCameraInfo();
						} else {
							this.loop = false;
						}
					}
				}, 500);
			},
			getCameraAuthInfo() {
				const that = this;
				uni.getSetting({
					success(res) {
						const authSetting = res.authSetting;
						if (authSetting['scope.camera']) {
							// 已经授权
							that.cameraEnable = true;
							
						} else {
							that.cameraEnable = false;
						}
					}
				});
			},

			errorCamera(e) {

				const that = this;
				uni.getSetting({
					success(res) {

						if (!res.authSetting["scope.camera"]) {
							uni.showModal({
								title: '提示',
								content: '请开启摄像头权限，否则无法拍照',
								confirmText: '去开启',
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											success(res) {
												if (res.authSetting["scope.camera"]) {
													
													that.getCameraAuthInfo();
												} else {

												}
											}
										})
									} else {
										return false;
									}
								}
							})
						}else{
							that.cameraEnable = true;
						}
					}
				})
			},


			takePhoto() {
				uni.showLoading({
					title: '拍摄中'
				})
				let _this = this;
				this.errorCamera();
				if (this.use_camera == 1) {

					this.cameraContext.takePhoto({
						quality: 'normal',
						async success(res) {
							//console.log('拍摄照片', res)
							let filePath = res.tempImagePath;
							console.log(filePath);

							let _date = new Date();
							let ext_name = filePath.substr(filePath.lastIndexOf('.'));
							let address = _date.getFullYear() + '' + (_date.getMonth() + 1) + '' + _date
								.getDate();
							let fileName = address + _date.getTime() + ext_name;
							console.log('---------', fileName)
							// console.log(res);
							// 图片信息：res.tempFilePaths 
							// 获取图片路径在页面上预览图片


							this.err = [];


							const img_info = await getImgInfo(filePath);
							console.log(img_info)
							let {
								width,
								height
							} = img_info;
							let maxWidth = 800;
							if (width > maxWidth) {
								let scale = Math.ceil(width / maxWidth);
								height = Math.ceil(height / scale);
								width = Math.ceil(maxWidth);
							}
							let compress_path = '';
							compress_path = await compressImg(filePath, {
								compressedWidth: width
							}).catch((res) => {
								console.log('上传压缩失败', err);
							});
							compress_path = compress_path ? compress_path : filePath;

							_this.upload_img(compress_path, fileName);

						},
						fail: (err) => {
							uni.hideLoading();
							uni.showToast({
								title: '拍照失败，请检查系统是否授权',
								icon: 'none',
								duration: 1200
							})
						}
					})
				} else {
					uni.chooseImage({
						count: 1,
						sourceType: ['camera'],
						async success(res) {

							// console.log(res);
							// 图片信息：res.tempFilePaths 
							// 获取图片路径在页面上预览图片


							this.err = [];
							//获取图片名字等信息 避免压缩后获取不到
							let filePath = res.tempFiles[0].path;

							let _date = new Date();
							let ext_name = filePath.substr(filePath.lastIndexOf('.'));
							let address = _date.getFullYear() + '' + (_date.getMonth() + 1) + '' + _date
								.getDate();
							let fileName = address + _date.getTime() + ext_name;
							const img_info = await getImgInfo(filePath);

							let {
								width,
								height
							} = img_info;
							let maxWidth = 800;
							if (width > maxWidth) {
								let scale = Math.ceil(width / maxWidth);
								height = Math.ceil(height / scale);
								width = Math.ceil(maxWidth);
							}
							let compress_path = '';
							compress_path = await compressImg(filePath, {
								compressedWidth: width
							}).catch((res) => {
								console.log('上传压缩失败', err);
							});
							compress_path = compress_path ? compress_path : filePath;

							_this.upload_img(compress_path, fileName);





						}
					})
				}





			},


			doSavePhoto(path) {
				path = this.rec_url + path;
				let now_photo = this.ai_photo;

				if (!now_photo) {
					let tmp = [];
					tmp.push(path);

					store.commit('userInfo/set_aiPhoto', tmp);

				} else {

					if (this.again == 1) {
						now_photo[this.from_index] = path;
					} else {
						now_photo.push(path);
					}


					store.commit('userInfo/set_aiPhoto', now_photo);

				}

				console.log('gogogo--------------------');
				//this.navigateTo(`/pagesB/photo/photo_step_3?spot_id=${this.spot_id}&points_id=${this.points_id}`)
				uni.redirectTo({
					url: `/pagesB/photo/photo_step_3?spot_id=${this.spot_id}&points_id=${this.points_id}&am=${this.again_model}`
				})

			},

			async upload_img(filePath, fileName) {
				try {
					uni.showLoading({
						title: '图片上传中',
					});

					const {
						file_url = ''
					} = await photoUploadFile(filePath, fileName, 'ai_group_photo')
						.finally(() => {
							uni.hideLoading();
						})
						.catch((res) => {

							uni.$u.toast('图片上传失败!!');
						});

					if (!file_url) {
						uni.$u.toast('图片上传失败!!!!!');
						return;
					}
					this.doSavePhoto(file_url);



				} catch (err) {
					console.log('图片上传失败', err);
					uni.$u.toast('上传照片失败~~');
					// this.message({ type: 'answer', data: '上传照片失败' });
				}
			},


		}
	}
</script>

<style lang="scss" scoped>
	@import './this.scss';

	image {
		width: 100%;
		height: 100%;
	}


	// ---------------step2---------------------
	.photo_back_1 {
		background-color: #000000;
		min-height: 100vh;
		width: 100%;
		top: 0;
		left: 0;
		height: 100%;
	}

	.photo_s2_1 {
		background-color: #fff;
		width: 100%;
		height: 800rpx;

	}

	.photo_s2_2 {
		width: 100%;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
		font-size: 32rpx;
		font-weight: 700;
		margin-top: 20rpx;
	}


	.photo_s2_3 {
		width: 90%;
		margin-left: 5%;
		display: flex;
		height: 38rpx;
		justify-content: space-around;
		align-items: center;
		margin-top: 20rpx;

		.photo_s2_3_one {
			display: flex;
			align-items: center;

			.photo_s2_3_one_1 {
				width: 32rpx;
				height: 32rpx;

				image {
					width: 100%;
					height: 100%;
				}

				margin-right: 10rpx;
			}

			.photo_s2_3_one_2 {
				color: #999999;
				font-size: 22rpx;

			}
		}
	}


	.photo_s2_4 {
		width: 90%;
		margin-left: 5%;
		display: flex;
		justify-content: space-between;
		margin-top: 32rpx;

		.photo_s2_4_one {
			width: 128rpx;

			.photo_s2_4_one_1 {
				width: 128rpx;
				height: 128rpx;
			}

			.photo_s2_4_one_2 {
				margin-top: 12rpx;
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.photo_s2_4_one_2_1 {
					width: 28rpx;
					height: 28rpx;
				}

				.photo_s2_4_one_2_2 {
					color: #fff;
					font-size: 22rpx;
					margin-top: 6rpx;
				}
			}
		}

	}

	.photo_s2_5 {
		width: 128rpx;
		height: 128rpx;
		margin: 32rpx auto;

	}

	.photo_s2_6 {
		height: 40rpx;
		width: 100%;
	}
</style>